package com.xyhuo.leetcode.november;

/**
 * N字形变换
 * https://leetcode.cn/problems/zigzag-conversion/
 *
 * @time 2023/11/29
 */
public class Convert {

//    public static void main(String[] args) {
//        Convert convert = new Convert();
////        convert.convert("PAYPALISHIRING", 4);
////        convert.convert("PAYPALISHIRING", 3);
//        convert.convert("A", 2);
//    }

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        char[] charArray = s.toCharArray();
        int len = charArray.length;
        StringBuilder sb = new StringBuilder();
        int plus = (numRows - 1) * 2;
        for (int i = 0; i < numRows; i++) {
            if (i >= len) {
                break;
            }
            sb.append(charArray[i]);
            int index = i;
            while (true) {
                if (i != 0 && i != numRows - 1) {
                    if (index - i * 2 + plus >= len) {
                        break;
                    }
                    sb.append(charArray[index - i * 2 + plus]);
                }
                if (index + plus >= len) {
                    break;
                }
                sb.append(charArray[index + plus]);
                index += plus;
            }
        }
        return sb.toString();
    }
}
